package com.econ.springboot.tdengine.demo.mybatis.service;

import com.econ.springboot.tdengine.demo.mybatis.dao.TagMapper;
import com.econ.springboot.tdengine.demo.mybatis.domain.TagData;
import com.taosdata.jdbc.TSDBDriver;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;

@Service
public class TagService {

    private final TagMapper tagMapper;

    public TagService(TagMapper tagMapper) {
        this.tagMapper = tagMapper;
    }

    private Random random = new Random(System.currentTimeMillis());

    public int init() {
        tagMapper.dropDB();
        tagMapper.createDB();
        tagMapper.createSuperTable();
        return 0;
    }


    /**
     * 初始化db
     * @return
     */
    public void initDB(){
        tagMapper.dropDB();
        tagMapper.createDB();
    }

    /**
     * 删除子表
     * @return
     */
    public void dropTable(String tableName){
        tagMapper.deleteTable(tableName);
    }

    /**
     * 删除超表
     * @return
     */
    public void dropSTable(String tableName){
        tagMapper.deleteTable(tableName);
    }

    /**
     * 默认是Tag作为超表
     * @param tagMap 表名称
     * @return
     */
    public void initTableWithTags(Map<Long, String> tagMap) {
//        for (int i = 0; i < tagNameList.size(); i++) {
            tagMapper.createBatchTable(tagMap);
//        }
    }


    /**
     *
     * @param limit
     * @param offset
     * @param tagName 这边表名就是测点名称
     * @return
     */
    public List<TagData> query(Long limit, Long offset,String tagName) {
        return tagMapper.selectByName(limit, offset,tagName);
    }

    public int save(String tagName, TagData tagData) {
        long ts = System.currentTimeMillis();
        return tagMapper.insert(tagName, tagData);
    }

    public long insertBatch(String tagName,List<TagData> tagDataList) {
        return tagMapper.insertBatch(tagName, tagDataList);
    }
    public int count() {
        return tagMapper.count();
    }

    public List<String> getAllTagNames() {
        return tagMapper.getAllTables();
    }

    public List<TagData> avg() {
        return tagMapper.avg();
    }




    public static void main(String[] args) throws SQLException {
        String jdbcUrl = "jdbc:TAOS://10.88.12.70:6030?user=root&password=taosdata";
        Properties connProps = new Properties();
        connProps.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
        connProps.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
        connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
        Connection conn = DriverManager.getConnection(jdbcUrl, connProps);
        System.out.println("Connected");
        conn.close();
    }
}
